/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pop3;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author epulapp
 */
public class MessageHandler {
    
    public HashMap<Integer, String> extractMessages(FileReader reader) {
        HashMap<Integer, String> files = null;
        try {
            files = new HashMap<Integer, String> ();
            char [] buffer = new char[1000];
            int readBytes = 0;
            
            StringBuilder sb = new StringBuilder();
            do {
                readBytes = reader.read(buffer);
                sb.append(buffer, 0, readBytes);
            } while (readBytes == 1000);
            
            String text = new String(sb);
            String [] messages = text.split("\r\n\\.\r\n");
            
            
            int count = 1;
            for (String message : messages) {
                
                files.put(count, message);
                count++;
            }
        } catch (IOException ex) {
            Logger.getLogger(MessageHandler.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(MessageHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
            return files;
        }
    }
    
    public String readMessage(BufferedReader reader) {
        char[]buffer = new char[1000];
        int readBytes = 0;
        
        StringBuilder sb = new StringBuilder();
        
        try {
            do {
                readBytes = reader.read(buffer);
                sb.append(buffer, 0, readBytes);
            } while (reader.ready());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(sb);
    }
}
